package com.gzy.mylog.security;

import com.gzy.mylog.model.User;
import com.gzy.mylog.server.AuthServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.util.StringUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class JWTFilter extends BasicAuthenticationFilter {


    private AuthServer authServer;

    public JWTFilter(AuthenticationManager authenticationManager, AuthServer authServer) {
        super(authenticationManager);
        this.authServer = authServer;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {

        // 验证 token
        String token = request.getHeader("Token");
        if (StringUtils.isEmpty(token)){
            chain.doFilter(request,response);
            return;
        }
        // 过滤之前做的事情
        User user = authServer.checkJWT(token);

        // 告诉 security 框架 当前用户是谁
        UserDetails userDetails = org.springframework.security.core.userdetails.User.builder()
                .password(user.getPassword())
                .username(user.getUsername())
                .roles(user.getRole())
                .build();



        Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());

        SecurityContextHolder.getContext().setAuthentication(authentication);

        chain.doFilter(request,response);

        // 过滤之后做的事情

    }
}
